<?php

class MsgcenterController extends ZendX_Controller_Action
{
	public function getNewestMsgAction($limit)
	{
		$res = array();
		$svc = new App_Service_Jsonp();
		
		$client = $this->couchClient();
		$msgs = $client->reduce(false)->limit($limit)->descending(true)->getView("services", "getNewestMsg");
	
    	$m_sec = 60;
    	$h_sec = 60*$m_sec;
    	$d_sec = 24*$h_sec; 
		$now = $this->now();
		$et = strtotime($now); 
		foreach ($msgs->rows as $v)
		{
			$time = '';
			$st = strtotime($v->value->create_at); 
			$td = $et - $st;
    	 	$d = floor($td/$d_sec);
    	 	$td -= $d*$d_sec;
    	 	$h =  floor($td/$h_sec);
    	 	$td -= $h*$h_sec;
    	 	$m = floor($td/$m_sec);
    	 	$td -= $m*$m_sec;
    	 	$s = $td;
    	 	
    	 	if ($d > 0) {
    	 		$time .= $d . "天";
    	 	}
    	 	
    	 	if ($h > 0) {
    	 		$time .= $h . "小时";
    	 	}
    	 	
    	 	if ($m > 0) {
    	 		$time .= $m . "分";
    	 	}
    	 	
    	 	if ($s > 0) {
    	 		$time .= $s . "秒";
    	 	}
    	 	
			if ($time == '')
            {
            	continue;
            }
            else
            {
            	$time = "在" . $time . "前";
            }
            
            $len = strlen($v->value->username);
            $username = '';
            if ($len > 2) {
            	$username = substr($v->value->username, 0, $len-2) . "xx";
            }
            elseif ($len > 1) {
            	$username = substr($v->value->username, 0, $len-1) . "xx";
            }
            else {
            	$username = $v->value->username . "xx";
            }
            
           	$res[] = array(
           		'username' => $username,
           		'time' => $time,
           		'msg' => $v->value->msg
           	);
		}
		
		echo $_GET["jsonpcallback"].'('.$svc->JSON(array('result' => $res)).')';
	}
}
?>